package scatter.common.rest.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import scatter.common.pojo.po.BasePo;
import scatter.common.pojo.vo.BaseVo;
import scatter.common.rest.exception.BusinessDataNoPrivilegeException;
import scatter.common.rest.exception.BusinessDataNotFoundException;
import scatter.common.rest.exception.BusinessException;
import scatter.common.rest.mapstruct.IBaseVoMapStruct;
import scatter.common.rest.service.IBaseAddFormService;
import scatter.common.rest.service.IBaseService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 通用带po的基础controller
 * </p>
 *
 * @author yangwei
 * @since 2020-10-12 12:49
 */
@Getter
public class BaseController<Po extends BasePo,Vo extends BaseVo> extends SuperController {


    @Autowired
    protected IBaseService<Po> iBaseService;

    @Autowired
    protected IBaseVoMapStruct<Po,Vo> voMapStruct;

    /**
     * 单表根据id获取
     * @param id
     * @return
     */

    public Vo queryById(String id){
        Po dbPo =  iBaseService.queryById(id);
        if (dbPo == null) {
            if (!iBaseService.existById(id)) {
                throw new BusinessDataNotFoundException(true);
            }
            throw new BusinessDataNoPrivilegeException (true);
        }
        return getVo(dbPo);
    }

    /**
     * 单表根据id删除
     * @param id
     * @return
     */

    public boolean deleteById(String id){
        boolean r = iBaseService.deleteById(id);
        if (!r) {
            if (!iBaseService.existById(id))  {
                throw new BusinessDataNoPrivilegeException(true);
            }
            throw new BusinessDataNotFoundException(true);
        }
        // 如果这里返回null，并不会被GlobalResponseBodyAdvice 统一包装
        return r;
    }

    /**
     * pos转vos
     * @param pos
     * @return
     */
    public List<Vo> posToVos(List<Po> pos) {
        if (pos == null) {
            return null;
        }
        return pos.stream().map(po->transVo(voMapStruct.poToVo(po))).collect(Collectors.toList());
    }

    /**
     * 分页po转vo
     * @param page
     * @return
     */
    public IPage<Vo> pagePoToVo(IPage<Po> page){
        IPage pageR = page;
        List<Po> records = pageR.getRecords();
        if (pageR != null && !isEmpty(records)) {
            pageR.setRecords(posToVos(records));
            return pageR;
        }
        // 原样返回page
        return pageR;
    }
    /**
     * 翻译vo的额外属性，如：字典id换名称，但一般提供了翻译注解，除非特别复杂的翻译直接手动写，否则直接实现ITransService接口即可
     * @param vo
     * @return
     */
    public Vo transVo(Vo vo){
        return vo;
    }

    public Vo getVo(Po po) {
        Vo vo = voMapStruct.poToVo(po);
        vo = transVo(vo);
        return vo;
    }

}
